package com.cunfang.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.cunfang.base.dao.DaoSupport;
import com.cunfang.entity.PageData;
import com.cunfang.entity.Tree;

import net.sf.json.JSONObject;

public class SysUtil {

	/**
	 * @功能：把list转换成树形(递归转换) @参数：files父级字段名称,fpid父级ID,filesid主键名称
	 */
	public static List<PageData> findPageInfo(List<PageData> list, String files, String fpid, String filesid) {
		List<PageData> newlist = new ArrayList<PageData>();
		List<String> listCon = new ArrayList<String>();
		String str;
		PageData pd;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getString(files).equals(fpid)) {
				pd = list.get(i);
				pd.put("nodes", findPageInfo(list, files, pd.getString(filesid), filesid));
				/* 判断重复... */
				str = list.get(i).getString(filesid);
				if (listCon.contains(str)) {
					continue;
				}
				listCon.add(str);

				newlist.add(pd);
			}
		}
		return newlist;
	}

	/**
	 * @功能：筛选当前角色的功能权限项
	 * @参数：froleid角色ID
	 */
	// public static List<PageData> findRightInfo(String froleid) {
	// List<PageData> list = SysCache.LISTRIGHT; /* 权限项缓存list */
	// List<PageData> newlist = new ArrayList<PageData>();
	// PageData pd;
	// for (int i = 0; i < list.size(); i++) {
	// if (list.get(i).getString("Role_ID").equals(froleid)) {
	// pd = (PageData) list.get(i).clone();
	// newlist.add(pd);
	// }
	// }
	// return newlist;
	// }

	/**
	 * @功能：把list转成功能权限树
	 * @作者：RC @日期：2016-08-14
	 */
	public static List<Tree> getTree(List<PageData> list, String pid) {
		List<Tree> listTreeNode = new ArrayList<Tree>();
		Tree treeNode;
		PageData hm;
		String strId;
		List<PageData> listNew = selectList(list, pid + "");
		for (int i = 0; i < listNew.size(); i++) {
			treeNode = new Tree();
			hm = listNew.get(i);
			strId = (String) hm.get("id");
			treeNode.setId(strId);
			treeNode.setName((String) hm.get("page_name"));
			treeNode.setChecked(Integer.parseInt(hm.get("fcheck") + "") == 1);
			if (strId.indexOf("FUNC") == -1) {
				treeNode.setNodes(getTree(list, strId));
			}
			listTreeNode.add(treeNode);

		}
		return listTreeNode;
	}

	/**
	 * @功能：根据条件查询 list 信息
	 * @作者：RC @日期：2015-08-06
	 */
	private static List<PageData> selectList(List<PageData> list, String key) {
		List<PageData> list1 = new ArrayList<PageData>();
		String str;
		for (int i = 0; i < list.size(); i++) {
			str = list.get(i).get("page_id") + "";
			if (key.equals(str)) {
				list1.add(list.get(i));
			}
		}
		return list1;
	}

	/**
	 * @功能：把list转成树形
	 * @作者：RC @日期：2016-09-02
	 */
	@SuppressWarnings({ "rawtypes" })
	public static List<Tree> getTreeInfo(List<PageData> list) {
		List<Tree> listTreeNode = new ArrayList<Tree>();
		Tree treeNode;
		/* 下级节点 */
		Tree temTree = new Tree();
		temTree.setId("0");
		temTree.setName(" ");
		List<Tree> temList = new ArrayList<Tree>();
		temList.add(temTree);
		HashMap hm;
		for (int i = 0; i < list.size(); i++) {
			treeNode = new Tree();
			hm = list.get(i);
			treeNode.setId(ConvertHashMapString(hm));
			treeNode.setName((String) hm.get("Name"));
			treeNode.setNodes(temList);
			listTreeNode.add(treeNode);
		}
		return listTreeNode;
	}

	/**
	 * @功能：传入code得到code的下级节点
	 * @作者：RC
	 */
	public static List<PageData> findByCodeUnitInfo(String code, String fCUCODE, String fcom) {
		if (SysCache.LISTUNIT == null)
			return null;
		List<PageData> list = new ArrayList<PageData>();
		PageData pd;
		/* 查找顶级节点 */
		if (code == null || code.length() == 0 || code.equals("null")) {
			for (int i = 0; i < SysCache.LISTUNIT.size(); i++) {
				pd = (PageData) SysCache.LISTUNIT.get(i);
				if (fCUCODE.equals(pd.getString("Code"))) {
					list.add(pd);
					return list;
				}
			}
		}
		/* 查找当前节点的下一级节点 */
		for (int i = 0; i < SysCache.LISTUNIT.size(); i++) {
			pd = (PageData) SysCache.LISTUNIT.get(i);
			if (pd.getString("Code").indexOf(fCUCODE) < 0) {
				continue;
			}
			if ("1".equals(fcom)) {
				String str = pd.getStrings("CategoryID");
				if ("1".equals(str) || "2".equals(str)) {
					if (pd.getString("Code").indexOf(code) > -1 && pd.getString("Code").length() - code.length() == 5) {
						list.add(pd);
					}
				}
			} else {
				if (pd.getString("Code").indexOf(code) > -1 && pd.getString("Code").length() - code.length() == 5) {
					list.add(pd);
				}
			}
		}
		return list;
	}

	/**
	 * @功能：把HashMap转成json字符串
	 * @作者：RC
	 */
	public static String ConvertHashMapString(HashMap hmMap) {
		String str = "";
		Map.Entry me;
		Iterator it = hmMap.entrySet().iterator();
		str = "{";
		while (it.hasNext()) {
			me = (Map.Entry) it.next();
			str += "\"" + me.getKey() + "\":\""
					+ (me.getValue() == null || (me.getValue() + "").length() == 0 || (me.getValue() + "") == "null"
							? "" : (me.getValue() + "").replaceAll("'", "‘"))
					+ "\",";
		}
		if (str.length() > 1) {
			str = str.substring(0, str.length() - 1); /* 去除逗号 */
		}
		str += "}";
		return str;
	}

	/**
	 * @功能：读取文本文件
	 * @作者：RC @日期：2016-04-11
	 */
	public static String readTxtFile(String filename) {
		try {
			String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))
					+ "../../"; /* 项目路径 */
			filePath = filePath.replaceAll("file:/", "");
			filePath = filePath.replaceAll("%20", " ");
			filePath = filePath.trim() + filename.trim();
			if (filePath.indexOf(":") != 1) {
				filePath = File.separator + filePath;
			}
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { /* 判断文件是否存在 */
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding); /* 考虑到编码格式 */
				BufferedReader bufferedReader = new BufferedReader(read);
				StringBuilder strb = new StringBuilder();
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					if (strb.toString().length() == 0) {
						strb.append(lineTxt);
					} else {
						strb.append("\n" + lineTxt);
					}
				}
				read.close();
				return strb.toString();
			} else {
				System.out.println("找不到指定的文件：" + filePath);
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
		}
		return "";

	}

	/**
	 * @功能：写入文件
	 * @作者：RC @日期：2016-04-11
	 */
	public static void writeTxtFile(String fileName, String content) {
		try {
			File file = new File(fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(content);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @功能：占位符替换
	 * @作者：RC @日期：2016-01-23
	 */
	public static String fillStringByArgs(String str, Object[] arr) {
		Matcher m = Pattern.compile("\\{(\\d)\\}").matcher(str);
		while (m.find()) {
			str = str.replace(m.group(), arr[Integer.parseInt(m.group(1))] + "");
		}
		return str;
	}

	/**
	 * @功能：把jsonobject转成PageData
	 * @作者：RC @日期：2016-11-04
	 */
	@SuppressWarnings("rawtypes")
	public static PageData ConvertJSONObjectInfo(JSONObject obj) {
		PageData pd = new PageData();
		Iterator it = obj.keys();
		while (it.hasNext()) {
			String key = it.next().toString();
			pd.put(key, obj.get(key));
		}
		return pd;
	}

	/**
	 * @功能：生成随机字符串
	 * @作者：RC @日期：2015-12-05
	 */
	public static String randomString(int length) {
		Random randGen = null;
		char[] numbersAndLetters = null;
		if (length < 1) {
			return null;
		}
		if (randGen == null) {
			randGen = new Random();
			numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
					.toCharArray();
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}
		return new String(randBuffer);
	}

	/**
	 * @功能：获得jsapi签名所需的的json字符串
	 * @作者：RC @日期：2016-12-16
	 */
	public static PageData GetJsApi_Signature(String url) throws Exception {
		PageData pd = new PageData();
		/* 1 时间戳 */
		String timestamp = (new Date()).getTime() + "";
		if (timestamp.length() > 10) {
			timestamp = timestamp.substring(0, 10);
		}
		timestamp = "1482111800";
		/* 2 微信appid */
		// String appid = Const.WXAPPID;
		String appid = "wx2753a7ba0891d884";

		/* 3 随机字符串 */
		String noncestr = randomString(16);
		noncestr = "Wm3WZYTPz0wzccnW";

		/* 4 生成唯一字符串 */
		// String ticket = ReadApi.getTicket("jsapi");
		String ticket = "kgt8ON7yVITDhtdwci0qedb10s8obtlEVPYfDQuRym-BVr2gKXpd7BMva33frPfSstQGBQTew47FHzvBo7Calg";

		String[] paramArr = new String[] { "jsapi_ticket=" + ticket, "timestamp=" + timestamp, "noncestr=" + noncestr,
				"url=" + url };
		Arrays.sort(paramArr);
		// 将排序后的结果拼接成一个字符串
		String content = paramArr[0].concat("&" + paramArr[1]).concat("&" + paramArr[2]).concat("&" + paramArr[3]);
		// SHA1签名生成
		String signature = getSHA1(content);
		// str = "{\"timestamp\":\"" + timestamp + "\",\"appId\":\""
		// + appid + "\",\"nonceStr\":\"" + noncestr + "\",\"signature\":\""
		// + signature + "\"}";
		pd.put("timestamp", timestamp);
		pd.put("appId", appid);
		pd.put("nonceStr", noncestr);
		pd.put("signature", signature);
		return pd;
	}

	/**
	 * SHA1签名生成
	 * 
	 * @param str
	 */
	public static String getSHA1(String str) throws Exception {
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		md.update(str.getBytes());
		byte[] digest = md.digest();

		StringBuffer hexstr = new StringBuffer();
		String shaHex = "";
		for (int i = 0; i < digest.length; i++) {
			shaHex = Integer.toHexString(digest[i] & 0xFF);
			if (shaHex.length() < 2) {
				hexstr.append(0);
			}
			hexstr.append(shaHex);
		}
		return hexstr.toString();
	}



	/**
	 * 组合生成角色菜单列表
	 * 
	 * @param menu
	 * @param list
	 * @return
	 */
	public static List<Tree> selectTree(List<PageData> menu, List<PageData> list) {	
		List<Tree> listTreeNode = new ArrayList<Tree>();
		Tree treeNode = null;
		List<PageData> tree = new ArrayList<PageData>();
		Set<String> persision = new HashSet<String>();
		for(PageData item:list){
			String id = item.getString("menu_id");
			persision.add(id);
		}
		for (int i = 0; i < menu.size(); i++) {
			//菜单等级
			PageData first = (PageData)menu.get(i);
			String menuId = (String) first.get("id");
			int grade =(Integer) first.get("menu_grade");
			if (grade == 1) {
					treeNode = new Tree();
					//菜单ID
					treeNode.setId(menuId);
					treeNode.setName((String)first.get("menu_name"));
					treeNode.setChecked(checkPersision(menuId, persision));
					List<Tree> Nodes = new ArrayList<Tree>();
					//判断二级菜单
					for(int j=i+1;j<menu.size();j++){
						Tree son = new Tree();
						PageData second =(PageData) menu.get(j);
						int grade2 =(Integer) second.get("menu_grade");
						if (grade2 == 2 && menuId.equals(second.getString("menu_father"))) {
							//菜单ID
							String menuId2 = (String) menu.get(j).get("id");
							son.setId(menuId2);
							son.setName((String)menu.get(j).get("menu_name"));
							son.setChecked(checkPersision(menuId2, persision));
							Nodes.add(son);
						}
					}
					if(Nodes != null){
						treeNode.setNodes(Nodes);
					}
					listTreeNode.add(treeNode);
			}
			
		}
		return listTreeNode;
	}
	
	public static boolean checkPersision(String menuId,Set<String> persision){
		if(persision.contains(menuId)){
			return true;
		}
		return false;
	}


}